from manim import *

'''
alpha increment per frame = 1/total_frames
total_frames = run_time * fps
low quality , fps = 15
'''
class Count(Animation):
    def __init__(self, number: DecimalNumber, start: float, end: float, **kwargs) -> None:
        super().__init__(number,  **kwargs)
        self.start = start
        self.end = end

        # 打开日志文件
        self.log_file = open("log.txt", "w")

    def interpolate_mobject(self, alpha: float) -> None:
        value = self.start + (alpha * (self.end - self.start))
        self.mobject.set_value(value)

        # 写入日志
        print(f"alpha={alpha:.3f}, value={value:.2f}", file=self.log_file)
        self.log_file.flush()  # 每次立即写入

    def finish(self):
        # 动画完成后关闭日志文件
        if hasattr(self, 'log_file') and not self.log_file.closed:
            self.log_file.close()


class CountingScene(Scene):
    def construct(self):
        number = DecimalNumber().set_color(WHITE).scale(5)
        number.add_updater(lambda number: number.move_to(ORIGIN))

        self.add(number)
        self.wait()

        count_anim = Count(number, 0, 100)
        self.play(count_anim, run_time=4, rate_func=linear)

        count_anim.finish()  # 关闭日志文件

        self.wait()
